
package wsepForum.network.client;

import java.util.Hashtable;
import javax.swing.JComponent;
import wsepForum.network.common.*;
import wsepForum.network.server.GUIToken;
import wsepForum.ui.swing.workers.ForumWorker;

/**
 * @author
 *
 */
public class GUIController {

	private SimpleClient client;
	private Hashtable<Integer,ForumWorker<? extends JComponent>> workerBySequence;
	private int sequenceID;

	public GUIController(){
		this.workerBySequence = new Hashtable<Integer, ForumWorker<? extends JComponent>>();
		this.sequenceID = 1;
	}

	public void setClient(SimpleClient clnt) {
		this.client = clnt;
	}

	public boolean sendRequest(GUIRequest request, ForumWorker<? extends JComponent> worker){
		String serializedRequest = RequestSerializer.serialize(request);
		this.workerBySequence.put(request.getSequenceID(), worker);
		return this.client.sendString(serializedRequest);
	}
	

	public void addInitialRequest(GUIRequest request, ForumWorker<? extends JComponent> worker){
		this.workerBySequence.put(request.getSequenceID(), worker);
	}
	

	public String incomingAnswer(GUIToken<GUIAnswer> token){
		GUIAnswer answer = token.getData();
		ForumWorker<? extends JComponent> worker = this.workerBySequence.get(answer.getSequenceID());
		if(worker != null){
			worker.putAnswer(answer);
		}
		return "";
	}
	
	public synchronized int getNextSequence(){
		return this.sequenceID++;
	}

}
